$(document).ready(function() {
  var $width = $('#content').width()
  var imgs = $('.imgs');
  var imageWidth = $width;
  var currentImg = 0;
  var maxImages = (imgs.children().length);//this needs to be dynamic
  var speed = 600;
  var captionWidth = $width;
  var caps;
  var speed = 400;
  var currentCaption;
  var $form = $('.form')
  , $inputAdd = $('input')
  , data;
  var $favButton = $('.fa.fav');
  var currentCaption = [];
  
  $form.toggle();

  $('.added-caption-fav').toggle()
  $('.removed-caption-fav').toggle()

  for (i = 0; i < maxImages; i++){
    currentCaption[i] = 0;
  }

  // console.log(captionWidth)
  // console.log("max images = " + maxImages);

  //------------------------------------------------------------------------------
  // IMAGE SWIPE
  //------------------------------------------------------------------------------

  function swipeImage(event, phase, direction, distance) {
    if( phase=="move" && (direction=="left" || direction=="right") ) {
      var duration = 0;
      if (direction == "left") {
        scrollImages((imageWidth * currentImg) + distance, duration);
      } else if (direction == "right"){
        scrollImages((imageWidth * currentImg) - distance, duration);
      }

    } else if ( phase == "cancel") {

      scrollImages(imageWidth * currentImg, speed);

    } else if ( phase == "end" ) {

      if (direction == "right")
        previousImage();
      else if (direction == "left")     
        nextImage();
      // checkCaption(0);//checking the first caption to see if it has favourite selected
    }
  }

  function previousImage() {
    currentImg = Math.max(currentImg - 1, 0);
    scrollImages( imageWidth * currentImg, speed);
    $form.hide();
  }

  function nextImage() {
    currentImg = Math.min(currentImg+1, maxImages-1);
    scrollImages( imageWidth * currentImg, speed);
    $form.hide();
  }

  $('.previous').on("tap", function(){
    console.log("previous image");
    previousImage();
  })

  $('.next').on("tap", function(){
    console.log("next image");
    nextImage();
  })

  function scrollImages(distance, duration) {
    imgs.css("-webkit-transition-duration", (duration/1000).toFixed(1) + "s");
    // inverse the number we set in the css
    var value = (distance<0 ? "" : "-") + Math.abs(distance).toString();
    console.log(value)
    imgs.css("-webkit-transform", "translate3d("+value +"px,0px,0px)");
  

  }

  //------------------------------------------------------------------------------
  // CAPTION SWIPE
  //------------------------------------------------------------------------------
  function swipeCaption(event, phase, direction, distance) {
    var caps = $($(this).find('.caps')[0])
    , maxCaps = $(this).find('.caps>ul>li').length;
    var curr = currentCaption[currentImg];
    console.log(curr);

      // if (!this.currentCaption) {
      //   this.currentCaption = 0;
      // }
      
      //If we are moving before swipe, and we are going L or R in X mode
      if( phase == "move" && (direction == "left" || direction == "right") ) {
        var duration = 0;

        if (direction == "left"){
          scrollCaptions(caps, (captionWidth * curr) + distance, duration);
        } else if (direction == "right") {
          scrollCaptions(caps, (captionWidth * curr) - distance, duration);
        }

      } else if ( phase == "cancel") {

        scrollCaptions(caps, captionWidth * curr, speed);

      } else if ( phase == "end" ) {

        if (direction == "right") {
          currentCaption[currentImg] = Math.max(curr - 1, 0);
        } else if (direction == "left") {
          currentCaption[currentImg] = Math.min(curr + 1, maxCaps - 1);
        }
        scrollCaptions(caps, captionWidth * currentCaption[currentImg], speed); 
        console.log(currentCaption);
        // checkCaption();  
      }

      $('.previous-cap').on("tap", function(){
        console.log("previous cap");
        currentCaption[currentImg] = Math.max(curr - 1, 0);
        scrollCaptions(caps, captionWidth * currentCaption[currentImg], speed);
      })

      $('.next-cap').on("tap", function(){
        console.log("next cap");
        currentCaption[currentImg] = Math.min(curr + 1, maxCaps - 1);
        scrollCaptions(caps, captionWidth * currentCaption[currentImg], speed);
      })
    }


  /**
  * Manually update the position of the imgs on drag
  */
  function scrollCaptions(caps, distance, duration) {
    caps.css("-webkit-transition-duration", (duration / 1000).toFixed(1) + "s");
    //inverse the number we set in the css
    var value = (distance < 0 ? "" : "-") + Math.abs(distance).toString();
    caps.css("-webkit-transform", "translate3d("+value +"px,0px,0px)");
  }

  //------------------------------------------------------------------------------
  // ADD CAPTION
  //------------------------------------------------------------------------------

  function addCaption(key) {
    console.log(key)
    var curContainer = $('.img-cap-container')[currentImg];
    var usersCaption = $('input').val();
    $(curContainer).find('.caps>ul').append('<li data-key="' + key + '">' + '<i class="fa fa-chevron-left previous-cap"></i><i class="fa fa-chevron-right next-cap"></i>' + '<span>' + usersCaption + '</span>'+ '</li>');

    // data[currentImg].captions.push({caption:usersCaption, fav:false});//passing object after creation
    $('#content .caps ul>li').css({'max-width' : $width , 'height' : 'auto'});
    // saveData();

    //automatically scroll to the caption that has been created and set the current image to the last one
    var totalCaps = $(curContainer).find('.caps>ul>li').length;
    var $caps = $($(curContainer).find('.caps')[0]);
    $caps.width(((totalCaps * captionWidth) + captionWidth) + "px"); //do this all the time//updated this to get the scroll captions to work properly
    scrollCaptions($caps, captionWidth * (totalCaps-1), speed)
    currentCaption[currentImg] = totalCaps-1
  }


  function submitCaption(){
    var data = new FormData();
    var imgKey = $($('.img-cap-container')[currentImg]).data('key');
    var usersCaption = $('input').val();
    data.append('key', imgKey);
    data.append('owncaption', usersCaption);
    console.log("Submit Caption", usersCaption)
    $.ajax({
      url: '/add-caption',
      type: "POST",
      data: data,
      processData: false,
      contentType: false
    }).error(function(e) {
      console.log('add', 'error', e);
    }).done(function (data) {
      addCaption(data.key);
      $form.fadeOut(1000);
      console.log('add', 'success', data);
    });
  }

  //------------------------------------------------------------------------------
  // FAVOURITE CAPTION AJAX CALL
  //------------------------------------------------------------------------------

  function favCaption(){
    var data = new FormData();
    var curContainer = $('.img-cap-container')[currentImg];
    var captions = $(curContainer).find('.caps>ul>li');
    var captionIndex = currentCaption[currentImg]
    var capSelect = captions[captionIndex]
    
    var key = $(capSelect).data("key")
    console.log("cap key" + key)
    data.append('key', key);
    
    //get the index to get the data from the element on the HTML DONE
    //check the status on the caption true or false - trun or not (cc)
    $.ajax({
      url: '/fav',
      type: 'POST',
      data: data,
      processData: false,
      contentType: false
    }).error(function(e){
      console.log("javascript error");
    }).done(function(data){
      console.log("im a asccess")
      if (data === "added favourite"){
        // alert("added a fav yo")
        // $favButton.addClass('favactivated');
        $('.added-caption-fav').toggle().fadeOut(3000)
        
      } else {
        // alert("deleted a fav yo")
        // $favButton.removeClass('favactivated');
        $('.removed-caption-fav').toggle().fadeOut(3000)

      }
      //status check the fav button on or off to change the status result

    })
  }

  //------------------------------------------------------------------------------
  // SET UP INIT FUNCTION TO SWIPE IMAGE AND CAPTION
  //------------------------------------------------------------------------------


  function initSwipe() {
    $(".image").swipe({
      triggerOnTouchEnd: true, 
      swipeStatus: swipeImage,
      allowPageScroll:"vertical",
      threshold:75      
    });

    $(".image-caption").swipe({
      swipeStatus: swipeCaption,
      triggerOnTouchEnd : true, 
      allowPageScroll:"vertical",
      threshold:75      
    });
  }


  //------------------------------------------------------------------------------
  // MOUSE AND KEYBOARD EVENT HANDLERS
  //------------------------------------------------------------------------------

  //clicking the button to add the caption
  $('.add-caption').on('click', function(e){
    e.preventDefault();
    console.log("add-caption clicked")
    submitCaption();
  });//end caption entering button 

  
  $('.add').on('click', function(){
    $form.fadeIn(1000);
    $inputAdd.focus();
    //clear the input text box on open again
    $inputAdd.val("");
    $('.form').prepend("<div class='close-form'><i class='fa fa-plus close-btn'></i></div>");
    $('.close-btn').on('click', function(){
      $form.fadeOut(1000);
    });

  });

  $('.fav').on('tap', function(e){
    e.preventDefault();
    console.log("tap")
    //toggleFav function call
    favCaption();
  });

  initSwipe();

  //image container width set dynamically according to the length/amount of image cap containers
  $('.imgs').each(function(){
    var len = $(this).find('.img-cap-container').length;
    $(this).width((len * imageWidth) + 'px');
    console.log("image length" + len)
  });

  //caption containers width set dynamically according to the length/amount of captions
  $('.caps').each(function (){
    var len = $(this).find('ul>li').length;
    $(this).width((len * captionWidth) + 'px');
    console.log("Cap length of image is: " + len)
  });
  //setting image and caption width dynamically according to the width of the device 
  $(document).ready(function() {
    $width = $('#content').width();
    $('#content .img-cap-container').css({'max-width' : $width, 'height' : 'auto'}); //TEMP FIX NOT RIGHT  
    $('#content .caps ul>li').css({'max-width' : $width , 'height' : 'auto'});
  });
});